package com.oe.market.modules.base.controller;


import cn.hutool.core.lang.Validator;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.google.gson.Gson;
import com.oe.market.modules.base.model.bean.Account;
import com.oe.market.modules.base.model.bean.RetResponse;
import com.oe.market.modules.base.model.bean.ServerInfo;
import com.oe.market.modules.base.model.dao.AccountDao;
import com.oe.market.modules.base.model.dto.AccountDto;
import com.oe.market.modules.base.model.dto.MailDto;
import com.oe.market.modules.base.service.AccountService;
import com.oe.market.modules.base.service.MailService;
import com.oe.market.modules.common.utils.Mail;
import com.oe.market.modules.common.validator.DtoValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/v1/base/account/")
public class AccountController {
    private static final Logger log = LoggerFactory.getLogger(AccountController.class);

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public String register(@RequestBody String data, HttpServletRequest request, HttpServletResponse response) {
        Gson gson = new Gson();
        RetResponse retResponse = RetResponse.failed("未知错误",null);
        try {
            AccountDto accountDto = gson.fromJson(data, AccountDto.class);
            try {
                DtoValidator.validate(accountDto);
            }
            catch (ValidationException e) {
                return e.getMessage();
            }

            AccountService accountService = new AccountService();
            Map ret = accountService.register(accountDto);
            if (ret.containsKey("error")) {
                retResponse.setMsg((String) ret.get("error"));
            }
            else {
                retResponse = RetResponse.success("成功", ret);
            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
            log.error("request: " + data);
            retResponse.setMsg("非法操作");
        }
        return gson.toJson(retResponse);
    }


    @RequestMapping(value = "/bind/mail", method = RequestMethod.POST)
    @ResponseBody
    public String bindMail(@RequestBody String body, HttpServletRequest request, HttpServletResponse response) {
        Account account = AccountService.check(request);
        if (null == account) {
            return RetResponse.failedByAccount().toString();
        }
        Gson gson = new Gson();
        MailDto mailDto = gson.fromJson(body, MailDto.class);
        try {
            DtoValidator.validate(mailDto);
        }
        catch (ValidationException e) {
            return e.getMessage();
        }

        try {
            if (MailService.me.bindUser(account.user, mailDto.mail)) {
                return RetResponse.success("验证邮件已经发送").toString();
            }
        }
        catch (Exception ignored) {
        }
        return RetResponse.failed().toString();
    }

    @RequestMapping(value = "/bind/mail/{user}/{verifyCode}")
    @ResponseBody
    public String bindMailVerify(@PathVariable("user")String user, @PathVariable("verifyCode") String verifyCode) {
        if (null == AccountDao.me.checkUser(user)){
            return RetResponse.failed().toString();
        }

        if (MailService.me.verifyUser(user, verifyCode)) {
            return RetResponse.success("绑定成功").toString();
        }
        return RetResponse.failed().toString();
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestBody String data, HttpServletResponse response) {
        Gson gson = new Gson();
        AccountDto accountDto = gson.fromJson(data, AccountDto.class);
        try {
            DtoValidator.validate(accountDto);
        }
        catch (ValidationException e) {
            log.error(e.getMessage());
            log.error("request: " + data);
            return e.getMessage();
        }


        RetResponse retResponse = null;
        try {
            AccountService accountService = new AccountService();
            String token = accountService.login(accountDto.user,accountDto.password);
            Map<String, String> ret = new HashMap<>();
            ret.put("current_sign", token);
            retResponse = RetResponse.success("成功",ret);

            // cookie
            response.addCookie(new Cookie("user",accountDto.user));
            response.addCookie(new Cookie("current_sign",token));
        }catch (Exception e) {
            log.error(e.getMessage());
            log.error("request: " + data);
            return RetResponse.failedByAccountLogin().toString();
        }
        return gson.toJson(retResponse);
    }
}
